package cn.bmyi.apiautotest.common;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 基于HttpURLConnection封装http请求
 * 
 * @author 毛建杰
 *
 */
public class Download
{
	/**
	 * 下载文件
	 * 
	 * @param url
	 *            url
	 * @param filePath
	 *            文件保存路径
	 */
	public static void fromUrl(String url, String filePath)
	{
		InputStream in;
		OutputStream out;

		// 创建Http连接connection
		HttpURLConnection connection;
		try
		{
			connection = (HttpURLConnection) (new URL(url)).openConnection();
		}
		catch (IOException e)
		{
			Logger.error(e.getMessage());
			return;
		}

		// 设置连接超时和读数据超时时间
		connection.setConnectTimeout(Config.timeout * 1000);
		connection.setReadTimeout(Config.timeout * 1000);

		// 发送http请求并返回InputStream
		try
		{
			in = connection.getInputStream();
		}
		catch (IOException e)
		{
			Logger.error(e.getMessage());
			return;
		}

		// 创建下载目录
		new File(filePath.split("(\\\\|/)[\\w\u4e00-\u9fa5]+\\.\\w+")[0]).mkdirs();

		// 写下载文件
		try
		{
			out = new BufferedOutputStream(new FileOutputStream(filePath));
			byte[] buffer = new byte[1024];
			int len;
			while ((len = in.read(buffer)) != -1)
			{
				out.write(buffer, 0, len);
			}
		}
		catch (IOException e)
		{
			Logger.error(e.getMessage());
			return;
		}

		// 关闭InputStream和OutputStream
		try
		{
			if (in != null)
			{
				in.close();
			}
			if (out != null)
			{
				out.close();
			}
		}
		catch (IOException e)
		{
			Logger.error(e.getMessage());
			return;
		}
	}
}
